import axios from 'axios'
import QS from 'qs'

// 全局baseUrl配置
if (process.env.NODE_ENV === 'development') {
  axios.defaults.baseURL = '/proxyApi'
} else if (process.env.NODE_ENV === 'production') {
  // axios.defaults.baseURL = 'https://api.test.ieaorg.cn/sunlands-app-api/'
} else {
  // axios.defaults.baseURL = 'https://api.test.ieaorg.cn/sunlands-app-api/'
}

export default class http {
  static async request (method, url, data, loading = false) {
    const params = {
      method,
      url,
      data
    }
    // try {
    const res = await axios(params)
    if (this.isSuccess(res)) {
      return res.data
    } else {
      throw this.requestExction(res)
    }
    // } catch (error) {
    //   console.log(JSON.parse(JSON.stringify(error)))
    //   if (JSON.parse(JSON.stringify(error)).response.status === 401) {
    //     store.commit('changeToken', {_Authorization: '', _p: ''})
    //     window.location.(window.location.href.split('#')[0] + '#/login')
    //   }
    // }
  }
  static isSuccess (res = {}) {
    let {
      status = 401
    } = res
    return status === 200
  }
  static requestExction (res) {
    return res
  }
  static get (url, data, loading = true) {
    return this.request('GET', url, data, loading)
  }
  static post (url, data, loading = true) {
    return this.request('POST', url, QS.stringify(data), loading)
  }
  static postWithParams (url, data, loading = true) {
    return this.request('POST', url, Object.assign(data, {
      _params_: true
    }), loading)
  }
}
